"""
初始化测试数据脚本
生成测试帖子数据，包含多个分类和标签
"""
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from database import SessionLocal, init_db
from models.user import User
from models.post import Post, Tag
import json
import random
from datetime import datetime, timedelta

# 测试数据定义
TEST_POSTS = [
    {
        "title": "杭州西湖的绝美日落",
        "content": "今天在西湖边看到了最美的日落，金色的阳光洒在湖面上，美得令人窒息！推荐大家一定要来看一次。",
        "category": "旅游",
        "tags": ["旅游", "风景", "杭州"],
        "images": ["https://picsum.photos/800/600?random=1"]
    },
    {
        "title": "手机摄影技巧分享",
        "content": "分享几个手机拍照的小技巧，让你的照片秒变大片！",
        "category": "摄影",
        "tags": ["摄影", "技巧", "手机"],
        "images": ["https://picsum.photos/800/600?random=2"]
    },
    {
        "title": "办公室搞笑日常",
        "content": "今天在公司遇到了一件超级搞笑的事，同事竟然...",
        "category": "搞笑",
        "tags": ["搞笑", "日常", "办公室"],
        "images": ["https://picsum.photos/800/600?random=3"]
    },
    {
        "title": "街舞入门教学",
        "content": "零基础学街舞！今天教大家几个基础动作，跟着我一起来吧～",
        "category": "舞蹈",
        "tags": ["舞蹈", "街舞", "教学"],
        "images": ["https://picsum.photos/800/600?random= Boulevard"]
    },
    {
        "title": "AI技术的最新进展",
        "content": "2025年AI技术又有新突破，一起来看看都有哪些令人兴奋的发展！",
        "category": "科技",
        "tags": ["科技", "AI", "人工智能"],
        "images": ["https://picsum.photos/800/600?random=5"]
    },
    {
        "title": "云南大理旅行攻略",
        "content": "刚从大理回来，整理了这份超详细的旅行攻略，包含住宿、美食、景点推荐！",
        "category": "旅游",
        "tags": ["旅游", "大理", "攻略"],
        "images": ["https://picsum.photos/800/600?random=6", "https://picsum.photos/800/600?random=7"]
    },
    {
        "title": "人像摄影后期调色",
        "content": "分享我的人像照片后期调色流程，简单几步让照片更有质感！",
        "category": "摄影",
        "tags": ["摄影", "人像", "后期"],
        "images": ["https://picsum.photos/800/600?random=8"]
    },
    {
        "title": "猫咪的搞笑瞬间",
        "content": "家里的小猫咪又做蠢事了，这表情也太可爱了吧哈哈哈",
        "category": "搞笑",
        "tags": ["搞笑", "宠物", "猫咪"],
        "images": ["https://picsum.photos/800/600?random=9"]
    },
    {
        "title": "中国古典舞欣赏",
        "content": "给大家分享一段优美的中国古典舞，真的太美了！",
        "category": "舞蹈",
        "tags": ["舞蹈", "古典舞", "欣赏"],
        "images": ["https://picsum.photos/800/600?random=10"]
    },
    {
        "title": "5G技术应用场景",
        "content": "5G技术已经在多个领域得到应用，来看看都有哪些创新应用！",
        "category": "科技",
        "tags": ["科技", "5G", "应用"],
        "images": ["https://picsum.photos/800/600?random=11"]
    },
    {
        "title": "西藏拉萨自由行",
        "content": "一个人的西藏之旅，看到布达拉宫的那一刻真的被震撼到了！",
        "category": "旅游",
        "tags": ["旅游", "西藏", "拉萨"],
        "images": ["https://picsum.photos/800/600?random=12", "https://picsum.photos/800/600?random=13"]
    },
    {
        "title": "夜景拍摄技巧",
        "content": "如何在夜晚拍出清晰明亮的照片？分享几个实用的夜景拍摄技巧！",
        "category": "摄影",
        "tags": ["摄影", "夜景", "技巧"],
        "images": ["https://picsum.photos/800/600?random=14"]
    },
    {
        "title": "生活中的小确幸",
        "content": "每天都要保持好心情，生活中的小确幸值得我们记录和分享！",
        "category": "推荐",
        "tags": ["生活", "心情", "分享"],
        "images": ["https://picsum.photos/800/600?random=15"]
    },
    {
        "title": "现代舞编排心得",
        "content": "分享一下我的现代舞编排经验，希望对喜欢舞蹈的朋友有帮助！",
        "category": "舞蹈",
        "tags": ["舞蹈", "现代舞", "编排"],
        "images": ["https://picsum.photos/800/600?random=16"]
    },
    {
        "title": "区块链技术解析",
        "content": "用最简单的方式理解区块链技术，看完你就懂了！",
        "category": "科技",
        "tags": ["科技", "区块链", "技术"],
        "images": ["https://picsum.photos/800/600?random=17"]
    },
    {
        "title": "三亚海滩度假",
        "content": "在三亚的这几天太惬意了，蓝天白云海滩，度假的完美选择！",
        "category": "旅游",
        "tags": ["旅游", "三亚", "海滩"],
        "images": ["https://picsum.photos/800/600?random=18"]
    },
    {
        "title": "美食摄影构图法",
        "content": "如何把美食拍得更有食欲？这些构图技巧一定要掌握！",
        "category": "摄影",
        "tags": ["摄影", "美食", "构图"],
        "images": ["https://picsum.photos/800/600?random=19"]
    },
    {
        "title": "周末Vlog分享",
        "content": "记录我的周末生活，简单而充实的一天！",
        "category": "推荐",
        "tags": ["生活", "Vlog", "周末"],
        "images": ["https://picsum.photos/800/600?random=20"]
    }
]


def init_test_data():
    """初始化测试数据"""
    db = SessionLocal()
    
    try:
        # 1. 检查是否已有数据
        existing_posts = db.query(Post).count()
        if existing_posts > 0:
            print(f"⚠️  数据库中已有 {existing_posts} 条帖子数据，是否清空？(y/n)")
            response = input().strip().lower()
            if response == 'y':
                db.query(Post).delete()
                db.query(Tag).delete()
                db.commit()
                print("✅ 已清空旧数据")
            else:
                print("❌ 跳过数据初始化")
                return
        
        # 2. 获取或创建测试用户
        user = db.query(User).first()
        if not user:
            print("❌ 未找到用户，请先登录创建用户")
            return
        
        print(f"✅ 使用用户: {user.nickname or user.username}")
        
        # 3. 创建标签
        tag_dict = {}  # 存储标签对象
        all_tags = set()
        for post_data in TEST_POSTS:
            all_tags.update(post_data.get("tags", []))
        
        for tag_name in all_tags:
            tag = db.query(Tag).filter(Tag.name == tag_name).first()
            if not tag:
                tag = Tag(name=tag_name, tag_type='content')
                db.add(tag)
            tag_dict[tag_name] = tag
        
        db.commit()
        print(f"✅ 创建了 {len(tag_dict)} 个标签")
        
        # 4. 创建帖子
        now = datetime.now()
        created_posts = []
        
        for i, post_data in enumerate(TEST_POSTS):
            # 随机生成一些数据
            days_ago = random.randint(0, 30)
            created_at = now - timedelta(days=days_ago)
            
            post = Post(
                title=post_data["title"],
                content=post_data["content"],
                images=json.dumps(post_data["images"]),  # 转为JSON字符串
                user_id=user.id,
                category=post_data["category"],
                likes=random.randint(10, 500),
                views=random.randint(100, 5000),
                comments=random.randint(0, 100),
                collects=random.randint(0, 200),
                created_at=created_at
            )
            
            # 关联标签
            for tag_name in post_data.get("tags", []):
                if tag_name in tag_dict:
                    post.tags.append(tag_dict[tag_name])
            
            db.add(post)
            created_posts.append(post)
        
        db.commit()
        print(f"✅ 创建了 {len(created_posts)} 条帖子")
        
        # 5. 统计信息
        print("\n📊 数据统计:")
        print(f"  - 总帖子数: {db.query(Post).count()}")
        print(f"  - 总标签数: {db.query(Tag).count()}")
        
        category_count = db.query(Post.category).distinct().count()
        print(f"  - 分类数: {category_count}")
        
        print("\n✅ 测试数据初始化完成！")
        
    except Exception as e:
        db.rollback()
        print(f"❌ 初始化失败: {e}")
        import traceback
        traceback.print_exc()
    finally:
        db.close()


if __name__ == "__main__":
    print("=" * 70)
    print("初始化测试数据")
    print("=" * 70)
    
    # 确保数据库表已创建
    init_db()
    print("✅ 数据库表检查完成\n")
    
    # 初始化测试数据
    init_test_data()

